package cn.springcloud.fix.common.core.support.concurrent;

import java.util.concurrent.ExecutionException;

public abstract class ListenableFutureAdapter<T, S> extends FutureAdapter<T, S> implements ListenableFuture<T> {

    protected ListenableFutureAdapter(ListenableFuture<S> adaptee) {
        super(adaptee);
    }

    @Override
    public void addCallback(final SuccessCallback<? super T> successCallback, final FailureCallback failureCallback) {
        ListenableFuture<S> listenableAdaptee = (ListenableFuture<S>) getAdaptee();//获取原始ListenableFuture

        listenableAdaptee.addSuccessCallback(result -> {
            T adapted;
            try {
                adapted = adaptInternal(result);
            } catch (ExecutionException ex) {
                Throwable cause = ex.getCause();
                failureCallback.onFailure(cause != null ? cause : ex);
                return;
            } catch (Throwable ex) {
                failureCallback.onFailure(ex);
                return;
            }
            successCallback.onSuccess(adapted);
        });

        listenableAdaptee.addFailureCallback(failureCallback);
    }
}
